// 权限控制
import { getProfileAPI } from './apis/user'
import router from './router'
import { useUserStore } from './stores/user'
import { getLocalToken } from './utils/auth'

const WHITE_LIST = ['/login', '/404']

/**
 * 处理一级路由数据
 */
const getFirstRoutePerms = (permsArr: string[]) => {
  const newArr = permsArr.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}

// 处理二级路由权限数据
const getSecondRoutePerms = (permsArr: string[]) => {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}

router.beforeEach(async (to, from, next) => {
  const token = getLocalToken()
  // 有token
  if (token) {
    next()
    const store = useUserStore()
    if(!store.profile.id){
      const res = await getProfileAPI()
      store.setProfile(res.data)
      console.log(res.data.permissions)
      const firstRoutePerms = getFirstRoutePerms(res.data.permissions)
      console.log(firstRoutePerms)
      const secondRoutePerms = getSecondRoutePerms(res.data.permissions)
      console.log(secondRoutePerms)
    }
  } else {
    // 没有token
    if (WHITE_LIST.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})